<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="500px"
    :before-close="handleClose"
  >
    <el-form
      status-icon
      ref="formDataRef"
      :rules="rules"
      :model="formData"
      label-width="100px"
      label-position="right"
      style="width: 400px"
    >
      <el-form-item label="分类名称:" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序:" prop="sort">
        <el-input-number
          style="width: 300px"
          v-model="formData.sort"
          :min="1"
          :max="10000"
        />
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('formDataRef')"
          size="mini"
        >
          确定</el-button
        >
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { ApiAdd, ApiSetId } from '@/api/category'
export default {
  props: {
    dialogVisible: { // 弹窗控制
      type: Boolean,
      default: false
    },
    formData: { // 表单数据
      type: Object,
      default: {}
    },
    title: {
      type: String,
      default: ""
    },
    remoteForm: Function
  },
  data () {
    return {
      rules: { // 校 验 规 则
        name: [ // 与 el-form-item 标签的 prop 属性值对应
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序号', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    handleClose () { // 关闭弹框
      this.$refs['formDataRef'].resetFields()
      this.remoteForm()
    },
    submitForm () { // 提交表单数据
      this.$refs['formDataRef'].validate(valid => {
        if (!valid) {
          return false
        }
        this.submitData()
      })
    },
    // 校验成功的方法
    async submitData () {
      let res = null
      // 判断是否存在id
      if (this.formData.id) { // 存在id 编辑操作
        res = await ApiSetId(this.formData)
      } else {
        // 新增操作
        res = await ApiAdd(this.formData)
      }
      if (res.code === 20000) {
        this.$message({
          message: '保存成功', type: 'success'
        })
        this.handleClose()
      } else {
        this.$message({
          message: '保存失败', type: 'error'
        })
      }
    }
  },
}
</script>

<style>
</style>